import axios, { AxiosInstance } from 'axios'
import { notBlankForString } from './blank-kit';
import { clearAccessToken, getAccessToken } from './token-kit'
import { Modal, message } from 'ant-design-vue'
import { createWebRouter } from '/@/router';
import { h } from 'vue';
import { t } from '/@/i18n/index'
import { LOGOUT_CODE, messageSuccessArr, successCodeArr } from '../framework/profile/code';
import { getLocale } from './i18n-kit';
import ServerError from '../components/qc/qc-error/server-error.vue'

const service: AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 500000,
    paramsSerializer: (params: any) => {
        if (params) {
            let result = '';
            Object.keys(params).forEach(key => {
                let val = params[key];
                if (!val) return;
                //把字符串作为 URI 组件进行编码 并且去掉其空格
                if (typeof (val) == 'string') {
                    result += `${key}=${encodeURIComponent(String(val).trim())}&`;
                } else if (val instanceof Object) {
                    result += key + "=" + JSON.stringify(val) + "&";
                } else {
                    result += key + "=" + val + "&"
                }
            });
            return result.substr(0, result.length - 1);
        }
    }
});

/**
 * token 超时后清理前端token信息 重置路由 并跳转登录页
 * @param responseData 
 */
const tokenInvalidAfter = (responseData: any) => {
    //清除前端保存的token信息
    clearAccessToken();
    Modal.error({
        title: t('kit.request.errorMessage'),
        content: responseData.msg,
        onOk() {
            createWebRouter();
            location.reload();
        }
    });
}

// request interceptor 在方法请求前插入token
service.interceptors.request.use(
    config => {
        //写入token
        let token = getAccessToken();
        if (notBlankForString(token)) config.headers['Access-Token'] = token;
        //写入语种
        let locale = getLocale();
        if (notBlankForString(locale)) config.headers['locale'] = locale;
        config.headers['Content-Type'] = 'application/json;charset=UTF-8'
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        var responseData = response.data;
        //如果他是blob文件则直接放行
        if (responseData instanceof Blob) return response;
        if (successCodeArr.indexOf(responseData.code) != -1) {
            if (messageSuccessArr.indexOf(responseData.code) != -1) {
                message.success(responseData.msg)
            }
            return response;
        } else if (responseData.code == LOGOUT_CODE) {
            tokenInvalidAfter(responseData);
        } else {
            // const arr = [h('p', responseData.msg)]
            // if (responseData.data) {
            //     //处理问题
            //     let mdate = responseData.data;
            //     if (responseData.causeMessage) {
            //         mdate += " ： " + responseData.causeMessage
            //     }
            //     arr.push(h('p', mdate))
            // }
            Modal.error({
                title: t('kit.request.errorTitle'),
                width: 1200,
                //content: h('div', {}, arr),
                content: h(ServerError, { errorData: responseData })
            });
            return Promise.reject(new Error(responseData.msg || 'Error'))
        }
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

export default service